package com.jar.exercise.多线程.AQS.CyclicBarrier;

import lombok.SneakyThrows;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class Main {

    static class ThreadTask implements Runnable {
        CyclicBarrier cyclicBarrier;

        public ThreadTask(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @SneakyThrows
        @Override
        public void run() {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() + "::到达A栅栏");
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName() + "::冲破A栅栏");
            TimeUnit.SECONDS.sleep(2);
            System.out.println(Thread.currentThread().getName() + "::到达B栅栏");
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName() + "::冲破B栅栏");

        }
    }

    public static void main(String[] args) {
        int threadCount = 5;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(threadCount, () -> {
            System.out.println(Thread.currentThread().getName() + "::完成最后任务！");
        });

        for (int i = 0; i < threadCount; i++) {
            new Thread(new ThreadTask(cyclicBarrier),"i::"+i).start();
        }

    }
}

